import readline
import cmd
import cnauth
from cnauth import CNAuth
from cnbooks import CNBooks
import evernote.edam.type.ttypes as Types
from cnconst import CNConst

class Clevernote(cmd.Cmd):
	""" Commandline interface to clevernote. Should run on Linux too """

	def __init__(self):
		cmd.Cmd.__init__(self)
		#need to login using command line parameters, maybe grab and cache list of notebooks
		
	def do_conn(self,userpass):
		up = userpass.split()
		if len(up)==2:
			self.auth = CNAuth()
			try:
				self.auth.authenticate(up[0],up[1])
				#need exception handling here
				print "Authentication was successful for ", self.auth.user.username
				print "Authentication token = ", self.auth.authToken
			except Exception, e:
						print 'failed to login', ', exception:', e
		else:
			print "conn <username> <password>"
			
	def do_ls(self,notebook):
		if not notebook:
			try:
				self.nb.notebooks
			except AttributeError:
				#create new notebooks object
				#will need a "sync" command to refresh it
				self.nb = CNBooks(self.auth.user,self.auth.authToken)
			print "Found ", len(self.nb.notebooks), " notebooks"
			for notebook in self.nb.notebooks:
				print notebook.name
		#else:
		#	#list notes in notebook
	
	def do_addbook(self,name):
		try:
			self.nb.notebooks
		except AttributeError:
			#create new notebooks object
			#will need a "sync" command to refresh it
			self.nb = CNBooks(self.auth.user,self.auth.authToken)
		newbook = Types.Notebook()
		newbook.name = name
		self.nb.noteStore.createNotebook(self.auth.authToken,newbook)
		self.nb.syncBooks(self.auth.authToken)

	def do_delbook(self,name):
		try:
			self.nb.notebooks
		except AttributeError:
			#create new notebooks object
			#will need a "sync" command to refresh it
			self.nb = CNBooks(self.auth.user,self.auth.authToken)
		for notebook in self.nb.notebooks:
			if notebook.name == name:
				guid = notebook.guid
		self.nb.noteStore.expungeNotebook(self.auth.authToken,guid)
		self.nb.syncBooks(self.auth.authToken)
		
	def do_exit(self, goal):
		return True
		
	#override oneCMD to check if self.auth exists before calling cmd, except for (conn)
		
if __name__ == '__main__':
	Clevernote().cmdloop()  
	

